package com.onpositive.datamap.core.impl;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.BitSet;
import java.util.Locale;

import com.onpositive.data.IPropertyConstants;
import com.onpositive.data.IPropertyMetadata;
import com.onpositive.data.diskstorage.AbstractValueAccessor;
import com.onpositive.datamap.IDataPropertyValue;
import com.onpositive.datamap.core.IDataProperty;
import com.onpositive.datamap.core.IScalarProperty;
import com.onpositive.datamap.values.impl.ScalarRange;

public class ScalarProperty extends DataProperty implements IScalarProperty {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public ScalarProperty(IPropertyMetadata meta,
			AbstractValueAccessor collection) {
		super(meta, collection);
	}

	@Override
	public IDataPropertyValue convert(Object value) {
		if (value != null) {
			return new ScalarRange(this, null, (Double) value);
		}
		return null;
	}
	
	@Override
	public Object aggregate(String aggregator, BitSet rs) {
		Object aggregate = super.aggregate(aggregator, rs);
		if (aggregate instanceof Number){
			Number br=(Number) aggregate;
			return newValue(br.doubleValue(),br.doubleValue(), "");
		}
		return aggregate;
	}

	@Override
	public String simpleType() {
		return IPropertyConstants.PROP_KIND_SCALAR;
	}

	@Override
	public Object adaptFilterValue(String c) {
		if (c.equalsIgnoreCase("none")||c.equalsIgnoreCase("-")){
			return -Double.MAX_VALUE/2;
		}
		if (c.equalsIgnoreCase("unknown")||c.equalsIgnoreCase("*")){
			return -Double.MAX_VALUE/3;
		
		}
		int indexOf = c.indexOf('-');
		if (indexOf!=-1){
			String substring = c.substring(0,indexOf);
			String substring1 = c.substring(indexOf+1);
			Object parse = parse(substring);
			Object parse1 = parse(substring1);
			if (parse instanceof Double&&parse1 instanceof Double){
				return newValue((Double)parse, (Double) parse1,null);
			}
			return newValue((Double)parse,(Double)parse,null);
		}
		Object parse = parse(c);
		if (parse==null){
			return null;
		}
		return newValue((Double)parse,(Double)parse,null);		
	}

	protected Object parse(String c) {
		try{
		return Double.parseDouble(c);
		}catch (NumberFormatException e) {
			try {
				return ((Number)NumberFormat.getInstance().parseObject(c)).doubleValue();
			} catch (ParseException e1) {
				try {
					return ((Number)NumberFormat.getInstance(Locale.US).parseObject(c)).doubleValue();					
				} catch (ParseException e2) {
					return null;
				}
				
			}
		}
	}

	@Override
	public ScalarRange newValue(double low, double high, Object comment) {
		return new ScalarRange(this, comment, low,high);
	}

	@Override
	public IDataProperty clone(AbstractValueAccessor va) {
		return new ScalarProperty(meta, va);
	}

	
}
